package stancel.peter.smslogger.background;

import java.util.List;

import stancel.peter.smslogger.R;
import stancel.peter.smslogger.SMSLogger;
import stancel.peter.smslogger.Sms;
import stancel.peter.smslogger.activities.MainActivity;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;

/**
 * Sluzba, ktora aktualizuje widget.
 * @author Peter Stancel
 */
public class SMSWidgetService extends Service{

	/**
	 * Ziska informacie o poslednej prijatej SMS a pomocou nich
	 * aktualizuje widget.
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget);
		
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
		remoteViews.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);

		SMSLogger smsLogger = (SMSLogger) getApplication();
		List<Sms> list = smsLogger.loadFromFile(smsLogger.getMaxFileNumber());
		if(!list.isEmpty()){
			Sms sms = list.get(0);
			String name = sms.getName();
			if(name == null){
				remoteViews.setTextViewText(R.id.widget_text_number, sms.getPhoneNumber());
			}else{
				remoteViews.setTextViewText(R.id.widget_text_number, name);
			}
			remoteViews.setTextViewText(R.id.widget_text_text, sms.getText());
			remoteViews.setTextViewText(R.id.widget_text_time, sms.getTime());
		}
		
		// aktualizacia widgetu
		ComponentName componentName = new ComponentName(this, SMSWidget.class);
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
		appWidgetManager.updateAppWidget(componentName, remoteViews);
		
		stopSelf();
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
